from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, GenericAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter
from rest_framework.viewsets import ViewSet
from drf_haystack.viewsets import HaystackViewSet
from django_redis import get_redis_connection

# Create your views here.
from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSerializer, SKUSearchSerializer, SKUHistorySerializer, SKUCommentsSerializer
from goods.utils import SKUPageNum
from orders.models import OrderGoods


class CategoriesView(APIView):
    """
        面包屑导航
    """

    def get(self, request, pk):
        try:
            cat3 = GoodsCategory.objects.get(id=pk)
        except:
            return Response({'error': '错误的分类id'})
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response(
            {
                'cat1': cat1.name,
                'cat2': cat2.name,
                'cat3': cat3.name
            }

        )


class SKUSView(ListAPIView):
    """
        列表页分类数据获取
    """
    # queryset = SKU.objects.filter(category_id=pk)
    serializer_class = SKUSerializer
    # 分页设置
    pagination_class = SKUPageNum
    # 排序设置
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


class SKUSearchView(HaystackViewSet):
    index_models = [SKU]
    serializer_class = SKUSearchSerializer
    pagination_class = SKUPageNum


class SKUHistoryView(CreateAPIView):
    """
        保存用户浏览历史记录和获取用户浏览历史记录
    """
    serializer_class = SKUHistorySerializer

    def get(self, request):
        # 1、获取用户
        user = request.user
        # 2、获取redis中当前用户的商品ID
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % user.id, 0, 100)  # [1,2,4]
        # 3、根据商品id查询商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        # 4、序列化返回商品数据
        ser = SKUSerializer(skus, many=True)
        return Response(ser.data)

class SKUCommentsView(APIView):

    def get(self,request,pk):

        try:
            order_goods = OrderGoods.objects.filter(sku_id = pk,is_commented = True).all()
        except:
            return Response("数据库操作失败")

        comment_list = []
        # comment_list['result'] = []
        for order_good in order_goods:
            sku_comment_dict = {}
            sku_comment_dict['comment'] = order_good.comment
            sku_comment_dict['score'] = order_good.score
            if order_good.is_anonymous == False:
                sku_comment_dict['username'] = order_good.order.user.username
            else:
                sku_comment_dict['username'] ="匿名用户"
            comment_list.append(sku_comment_dict)

        # return Response(comment_list)

        ser = SKUCommentsSerializer(comment_list, many=True)
        return Response(data = {'result':ser.data})





        # print(ser.data)

